package com.manage.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;

import android.util.Log;

public class StringUtil {

	// 自定义的字符串翻转方法。
	// 很多第三方的包的都有实现，但是 Java API 没有实现，这里自己实现一下 ^_^
	public static String reverse(String str) {
		char[] charsOld = str.toCharArray();

		char[] charsNew = new char[charsOld.length];

		int index = charsOld.length - 1;

		for (int i = 0; i < charsOld.length; i++) {

			charsNew[i] = charsOld[index - i];
		}

		return String.valueOf(charsNew);
	}

	/**
	 * 由于服务器返回的json格式是有问题的，在这里处理下
	 */
	public static String getJsonString(String paramString) {
		int startIndex = paramString.indexOf(":") + 1;
		int endIndex = paramString.length() - 2;
		return paramString.substring(startIndex, endIndex);
	}

	/**
	 * 特么的，格式竟然不一至，又要截取字符串了
	 * @param paramString
	 * @return
	 */
	public static String getJsonString2(String paramString) {
		String tempStr = paramString.substring(paramString.indexOf(",") + 1, paramString.length());
		
		return tempStr.substring(tempStr.indexOf(":") + 1, tempStr.length() - 2);
	}
	
	public static boolean hasCount(String paramString) {
		if(paramString.startsWith("count", 3)) {
			return true;
		}
		else {
			return false;
		}
	}
	
	public static JSONArray getJson(String paramString) {
//		if(hasCount(paramString)) {
//			paramString = getJsonString2(paramString);
//		}
//		else {
			paramString = getJsonString(paramString);
//		}
		
		Log.i("JSONArray", paramString);
		
		String[] res = paramString.split("_return_info\":");

		JSONArray array = new JSONArray();

		// Log.i(TAG, ":" + res.length);

		for (int i = 0; i < res.length; i++) {
			if (i == res.length - 1) {
				try {
					array.put(i, res[i]);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				// Log.i(TAG, "2:"+ res[i] + "\n");
				break;
			}

			String tempString = res[i].trim();
			tempString = StringUtil.reverse(tempString);

			int startIndex = tempString.indexOf(",");
			int endIndex = tempString.length();

			String tempString2 = res[i].substring(0, endIndex - startIndex - 1);

			try {
				array.put(i, tempString2);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			// Log.i(TAG, ":"+ tempString2 + "\n");
		}
		// Log.i(TAG, ":"+ array.length() + "\n");
		// Log.i(TAG, ":"+ array.toString() + "\n");

		return array;
	}

	public static boolean isPhoneNumberValid(String phoneNumber) {

		boolean isValid = false;
		String expression = "^//(?(//d{3})//)?[- ]?(//d{3})[- ]?(//d{5})$";
		String expression2 = "^//(?(//d{3})//)?[- ]?(//d{4})[- ]?(//d{4})$";
		CharSequence inputStr = phoneNumber;

		Pattern pattern = Pattern.compile(expression);

		Matcher matcher = pattern.matcher(inputStr);

		Pattern pattern2 = Pattern.compile(expression2);

		Matcher matcher2 = pattern2.matcher(inputStr);

		if (matcher.matches() || matcher2.matches()) {
			isValid = true;
		}

		return isValid;

	}
}
